import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken, setToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import Axios from 'axios'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login'] // no redirect whitelist

let n = 0;


router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)
  

  // determine whether the user has logged in
  const hasToken = getToken()
  console.log(hasToken)

  const urlParams = new URLSearchParams(window.location.search);
  // console.log(window.location)
  // console.log(urlParams)
  const jsonDataParam = urlParams.get('data');
  // console.log(jsonDataParam)

  // 设置成功后，你可能想要移除 URL 参数，以防用户刷新页面时再次执行这个逻辑
  const urlWithoutDataParam = window.location.origin + window.location.pathname;
  window.history.replaceState({}, document.title, urlWithoutDataParam);



  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/' })
      NProgress.done()
    } else {
      const hasGetUserInfo = store.getters.name
      if (hasGetUserInfo) {
        next()
      } else {
        try {
          // get user info
          await store.dispatch('user/getInfo')

          next()
        } catch (error) {
          // remove token and go to login page to re-login
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    /* has no token*/

    //生产环境
    // if (jsonDataParam) {
    //   // console.log("setToken")
    //   n +=1;
    //   try {
    //     // 解析 JSON 数据
    //     const jsonData = JSON.parse(decodeURIComponent(jsonDataParam));
    //     // console.log(jsonData)

    //     // 提取 token 字段
    //     const token = jsonData.token;
    //     // console.log(token)

    //     if (token) {
    //       // 使用你的 setToken 函数将 token 设置到 Cookie 中
    //       setToken(token);

    //       // 设置成功后，你可能想要移除 URL 参数，以防用户刷新页面时再次执行这个逻辑
    //       // const urlWithoutDataParam = window.location.origin + window.location.pathname;
    //       // window.history.replaceState({}, document.title, urlWithoutDataParam);
    //       // router.replace('/')
    //     }
    //   } catch (error) {
    //     console.error('Error parsing JSON data:', error);
    //     // 解析错误时，跳转到登录页
    //     next('/prod-api/openid/login');
    //   }
    // }

    // // console.log(n);
    // if (n === 0) {
    //   window.location.href = '/prod-api/openid/login';
    //   // next(`/login?redirect=${to.path}`)
    // } else {
    //   location.reload();
    // }
    // NProgress.done();

      
    





    //debug环境
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      // const loginRedirectURL = 'http://localhost:8080/prod-api/openid/login'
      // next(`/login?redirect=${encodeURIComponent(loginRedirectURL)}`)
      next(`/login?redirect=${to.path}`)
      // window.location.href = '/prod-api/openid/login';
      NProgress.done()
    }



  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
